#!/bin/sh

start=$(date +%s)
printf "%s: start\n" "`date`"

# ALL VARIABLES STARTING WITH % WILL BE REPLACED BY BUTCH
# WITH VALUES TAKEN FROM THE PKG FILE.

# BUTCH_CONFIG will get replaced by the environment variables
# that butch uses (R,S,C...).
%BUTCH_CONFIG
BUTCH_HAVE_TARBALL=false
[ -n "%BUTCH_MIRROR_URLS" ] && BUTCH_HAVE_TARBALL=true
get_file_name() {
printf "%s" "$1" | awk '{n=split($0,a,"/");print a[n];}'
}
strip_file_ext() {
case "$1" in
*.tar.*) printf "%s" "$1"| sed 's/\.tar\.[0-9a-z]*$//' ;;
*) le=$(printf "%s" "$1"| awk '{n=split($0,a,".");print a[n];}' | wc -c)
   ls=$(printf "%s" "$1"|wc -c)
   l=$(($ls - $le))
   printf "%s" "$1"|cut -b -$l
   ;;
esac
}
if [ -z "$tarball" ] && $BUTCH_HAVE_TARBALL ; then
for i in %BUTCH_MIRROR_URLS ; do
	tarball=$(get_file_name "$i")
	break
done
fi

BUTCH_TARBALL="$tarball"
if [ -z "$tardir" ] && $BUTCH_HAVE_TARBALL ; then
	tardir=$(strip_file_ext "$tarball")
fi
BUTCH_TARDIR="$tardir"

[ -z "$B" ] && B=$S/build

# some settings to influence this script...
# note that you could set similar stuff using env variables.
butch_do_config_cache=true
butch_do_cleanup_builddir=true
butch_do_custom_destdir=true
# the options below all require a custom destdir to be set.
butch_do_cleanup_custom_destdir=true
[ -z "$butch_do_relocate" ] && butch_do_relocate=true
butch_do_filelists=true
butch_do_create_tarball=false
butch_do_separate_debug_info=true
[ -z "$butch_do_overwrite_on_copy" ] && butch_do_overwrite_on_copy=false

[ -z "$butch_filelists" ] && butch_filelists="$S/filelists/"
[ -z "$butch_tarballs_used" ] && butch_tarballs_used="$S/tarballs_used.txt"
butch_created_tarball_dest="$S/dist/"

butch_package_name=%BUTCH_PACKAGE_NAME
butch_prefix=/

filelist="$butch_filelists/$butch_package_name.txt"

# making the prefix empty instead of / seems like a good idea to not get ugly double slashes
# when concatenating paths. however this leads to multiple issues in buggy packages,
# but these have been fixed now (see openssl-dynamic, perl, xcb-proto for reference).
[ "$butch_prefix" = "/" ] && butch_prefix=
# butch_root_dir contains the root path passed in $R.
# once inside the chroot, it is /. we use the butch variable in case a script overwrites $R,
# and in order to be able to swap it out easily once i decided to replace the variables with
# a config file or so.
# use it, if you need to reference something that lies in the directory structure.
butch_root_dir="$R"
[ "$butch_root_dir" = "/" ] && butch_root_dir=
butch_custom_destdir_base=/opt/$butch_package_name
butch_custom_destdir="$butch_root_dir""$butch_custom_destdir_base"

#currently passing a version from a package is not implemented.
butch_package_version=0.0.0

# if we unlink busybox, gcc4 or binutils, nothing will work anymore
for i in busybox coreutils gcc454 gcc424 gcc447 gcc463 gcc464 gcc472 gcc473 gcc474 gcc485 gcc493 gcc520 binutils musl-git musl sed make grep ; do
	[ "$butch_package_name" = "$i" ] && butch_do_cleanup_custom_destdir=false
done

# butch_install_dir denotes the DESTDIR passed to make
if $butch_do_custom_destdir ; then
	butch_install_dir="$butch_custom_destdir"
	if $butch_do_cleanup_custom_destdir ; then
		rm -rf "$butch_custom_destdir"
		if [ "$butch_do_filelists" ] && [ -e "$filelist" ] ; then
			"$K"/bin/butch-unlink "$butch_package_name"
			rm -f "$filelist"
		fi
	fi
else
	butch_install_dir=""
	butch_do_relocate=false
fi
[ -z "$butch_install_dir" ] || mkdir -p "$butch_install_dir"

#butch_cache_dir is the place where tarballs are found
butch_cache_dir="$C"

# this is were stuff gets extracted to and built in
butch_build_root="$B/$butch_package_name"
butch_build_dir="$butch_build_root/$BUTCH_TARDIR"

#this is the location of our optimized config.cache
butch_configure_cache="$K/config.cache"

[ -z "$CC" ]  && CC=cc
[ -z "$CXX" ]  && CXX=c++
[ -z "$HOSTCC" ]  && HOSTCC="$CC"
[ -z "$HOSTCXX" ]  && HOSTCXX="$CXX"

user_optimizations_file="$butch_root_dir"/etc/butch-optflags.sh
debug_build=0
if [ -e "$user_optimizations_file" ] ; then
	printf "sourcing user defined optimization config %s\n" "$user_optimizations_file"
	. "$user_optimizations_file"
	printf "%s\n" "$optcflags" | \
		grep -E '(^|\s)[-]g[123]*($|\s)' >/dev/null && \
		debug_build=1
else
	printf "user optimization file %s not found.\n" "$user_optimizations_file"
fi

if $butch_do_cleanup_builddir && [ -e "$butch_build_dir" ] ; then
	rm -rf "$butch_build_dir"
fi
[ -d "$butch_build_root" ] || mkdir -p "$butch_build_root"
cd "$butch_build_root"

# BUTCH_HAVE_TARBALL will be replaced by true or false
# depending on whether a tarball is used by the pkg
if $BUTCH_HAVE_TARBALL ; then

	printf '%s\n' "$BUTCH_TARBALL" >> "$butch_tarballs_used"
	printf "%s: starting to untar\n" "`date`"
	if echo $BUTCH_TARBALL | grep -q "\.xz" ; then
		tarflags=xJf
	elif echo $BUTCH_TARBALL | grep -q "\.lzma" ; then
		tarflags=xaf
	elif echo $BUTCH_TARBALL | grep -q "\.bz2" ; then
		tarflags=xjf
	else
		tarflags=xzf
	fi
	if ! tar $tarflags "$butch_cache_dir/$BUTCH_TARBALL" ; then
		case "$BUTCH_TARBALL" in
			*.tar.xz)
				# old gnu tar passes .xz to lzma instead of xz
				if ! xz -dc "$butch_cache_dir/$BUTCH_TARBALL" | tar x ; then
					echo "tarball error"
					exit 1
				fi ;;
			*.tar.*)
				echo "tarball error"
				exit 1 ;;
			*)
				echo "seems we're not dealing with a tarball"
				echo "handing control to package file..." ;;
		esac
	fi
	printf "%s: untar done\n" "`date`"
	cd "$butch_build_dir"

	# this copies a config.cache template (gets installed by pkg/config-cache)
	# into the actual builddir, so configure skips some timewasting tests
	if $butch_do_config_cache ; then
		[ -e "$butch_configure_cache" ] && cp -f "$butch_configure_cache" . || true
	fi
fi

printf "%s: start build\n" "`date`"
# this will be replaced by the contents of the pkg's [build] section.
# note that all critical commands in the buildscript should use || exit 1
# so that it aborts on error!
set -e
%BUTCH_BUILDSCRIPT
set +e

printf "%s: end build\n" "`date`"
echo "post buildscript phase..."

# a package that doesn't want to be handled by the code below this line
# can just call exit 0 as the last statement
# if it wants to get some other stuff handled it could simply override
# butch_install_dir (e.g. for sabotages relocate_toolchain script)
cd "$butch_install_dir"
[ `ls | wc -l` = "0" ] && have_files=false || have_files=true
[ -d share/pkgconfig ] && {
echo "error: package installed pkgconfig files into /share"
echo "please fix package (examples: xtrans eudev libyajl usbutils shared-mime-info)"
exit 1
}
if $have_files ; then
	if $butch_do_separate_debug_info && [ "$debug_build" = 1 ] ; then
		printf "stripping debug info into external files..."
		mkdir -p lib/debug && chmod 775 lib/debug
		for i in lib/*.so* bin/* ; do
			printf "%s" "$i" | grep '\*'>/dev/null && continue
			[ -L "$i" ] || [ -d "$i" ] && continue
			case "$i" in bin*)
				elf=$(dd if="$i" bs=1 skip=1 count=3 2>/dev/null)
				[ "$elf" != "ELF" ] && continue
			esac
			name=$(printf "%s" "$i" | sed 's@/@_@')
			"$CROSS_COMPILE"objcopy --only-keep-debug "$i" lib/debug/"$name".dbg &&
			"$CROSS_COMPILE"strip --strip-debug --strip-unneeded "$i" &&
			"$CROSS_COMPILE"objcopy --add-gnu-debuglink=lib/debug/"$name".dbg "$i"
		done
		chmod 664 lib/debug/*
		echo done
	fi

	# here you could place some code that makes a tarball out of $butch_install_dir
	# moves the contents to / or create some sort of package file list.
	# e.g.
	if [ "$butch_do_filelists" ] ; then
		mkdir -p "$butch_filelists"
		echo "creating filelist $filelist"
		find . -type f -or -type l > "$filelist"
	fi

	if $butch_do_relocate ; then
		# now we make a symlink from each file into butch_prefix
		"$K"/bin/butch-relocate "$butch_package_name"
	fi

	if $butch_do_create_tarball ; then
		mkdir -p "$butch_created_tarball_dest"
		tarball="$butch_created_tarball_dest/$butch_package_name-$package_version-$A.tar.bz2"
		echo "creating dist tarball $tarball"
		tar cjf "$tarball" *
	fi

fi

printf "%s: done.\n" "`date`"
[ -n "$start" ] && printf "total build time: %d seconds.\n" $(($(date +%s) - $start))
